package org.lex.elec.apps;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//FIXME
public class Prefs {
	public static final String KEY_LNF = "application.lnf";
	public static final String KEY_SUDOKU_HINT = "sudoku.hint";

	private static final String CONFIG_FILE_NAME = "sudoku.conf";

	private final File storageRoot;
	private Properties config = null;
	private final Logger log = LoggerFactory.getLogger(Prefs.class);

	public Prefs(File storageRoot) {
		this.storageRoot = storageRoot;
	}

	public Properties getConfig() {
		if (null == this.config) {
			this.config = this.loadConfig();
		}
		return config;
	}

	private Properties loadConfig() {
		Properties props = new Properties();
		File file = new File(this.storageRoot, Prefs.CONFIG_FILE_NAME);
		if (file.exists() && file.isFile() && file.canRead()) {
			try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));) {
				props.load(in);
			} catch (Exception e) {
				log.warn("load & read config file[" + Prefs.CONFIG_FILE_NAME
						+ "] failed: file not exists or file format error?", e);
			}
		}
		return props;
	}

	public void storeConfig() {
		Properties props = this.getConfig();
		File dir = this.storageRoot;
		File file = new File(dir, Prefs.CONFIG_FILE_NAME);
		BufferedOutputStream out = null;
		try {
			if (false == file.exists() || false == file.isFile()) {
				if (false == dir.exists() || false == dir.isDirectory()) {
					dir.mkdirs();
				}
				file.createNewFile();
			}
			out = new BufferedOutputStream(new FileOutputStream(file));
			props.store(out, "DO NOT EDIT! This is application config file.");
			out.flush();
		} catch (Exception e) {
			log.warn("write config file[" + Prefs.CONFIG_FILE_NAME + "] failed", e);
		} finally {
			if (null != out) {
				try {
					out.flush();
				} catch (Exception e) {
					log.warn("flush config file[" + Prefs.CONFIG_FILE_NAME + "] failed", e);
				} finally {
					try {
						out.close();
					} catch (Exception e) {
						log.warn("close config file[" + Prefs.CONFIG_FILE_NAME + "] failed", e);
					}
				}
			}
		}
	}
}